#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include <cstring>
#include "Commend.hpp"
#include "UdpAddr.hpp"
using namespace log_ns;
class udpclient
{
public:
    udpclient(u_int16_t server_port, std::string server_ip)
        : _isrunning(false), _server_port(server_port), _server_ip(server_ip)
    {
    }

    void InitClient()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "<client> socket error,error information: %s\n", strerror(errno));
            exit(APPLY_SOCKET_ERROR);
        }
        LOG(DEBUG, "<client> socket application success\n");
    }
    void Start()
    {
        _isrunning = true;
        std::string massage;
        sockaddr_in _server_addr;
        memset(&_server_addr, 0, sizeof(_server_addr));
        _server_addr.sin_family = AF_INET;
        _server_addr.sin_port = htons(_server_port); // 这里转换过了
        _server_addr.sin_addr.s_addr = inet_addr(_server_ip.c_str());

        char buffer[1024];
        while (_isrunning)
        {

            sockaddr_in addrget;
            socklen_t len = sizeof(addrget);

            std::cout << "plase enter a word:";
            getline(std::cin, massage);

            if (massage == "quit" || massage == "exit")
            {
                LOG(INFO, "<client> client quit!\n");
                exit(0);
            }

            int n = sendto(_sockfd, massage.c_str(), massage.size(), 0, (sockaddr *)&_server_addr, sizeof(_server_addr));
            if (n < 0)
            {
                LOG(FATAL, "<client> sendto error, error infomation: %s\n", strerror(errno));
                exit(SENDTO_ERROR);
            }
            else
            {
                LOG(DEBUG, "<client> sendto infomation: %s\n", massage.c_str());
            }

            n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&addrget, &len);
            addr_t who(addrget);
            if (n < 0)
            {
                LOG(FATAL, "<client> revcfrom error, error infomation: %s\n", strerror(errno));
                exit(RECVFORM_ERROR);
            }
            else
            {
                buffer[n] = 0;
                LOG(DEBUG, "<client> recvfrom infomation: %s\n", buffer);
            }
            std::cout << buffer << std::endl;
        }

        ::close(_sockfd);
    }
    ~udpclient() {}

private:
    int _sockfd;
    u_int16_t _server_port;
    std::string _server_ip;
    bool _isrunning;
};